package com.qyhl.shop.shop.rush.detail.order;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.lihang.ShadowLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.shop.common.ShopConfig;
import com.qyhl.shop.view.PayPopupWindow;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.Md5Builder;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.AuthResult;
import com.qyhl.webtv.commonlib.entity.shop.ShopGiftDetailBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopPayResultBean;
import com.qyhl.webtv.commonlib.utils.PayResult;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.weavey.loading.lib.LoadingLayout;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_GIFT_ORDER)
public class ShopOrderActivity extends BaseActivity implements ShopOrderContract.ShopOrderView {
    @BindView(R2.id.bottom_price)
    TextView bottomPrice;
    @BindView(R2.id.shop_name)
    TextView shopName;
    @BindView(R2.id.cover)
    RoundedImageView cover;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.price)
    TextView price;
    @BindView(R2.id.date)
    TextView date;
    @BindView(R2.id.address)
    TextView address;
    @BindView(R2.id.introduction)
    TextView introduction;
    @BindView(R2.id.order_num)
    TextView orderNum;
    @BindView(R2.id.order_time)
    TextView orderTime;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.count_down)
    TextView countDown;
    @BindView(R2.id.count_down_layout)
    ShadowLayout countDownLayout;

    @Autowired(name = "id")
    int userGiftId;

    @Autowired(name = "isMine")
    boolean isMine;

    private CountDownTimer countDownTimer;

    private ShopGiftDetailBean detailBean;

    private ShopOrderPresenter mPresenter;

    private PayPopupWindow payPopupWindow;

    private int payType;

    private ShopPayResultBean payResultBean;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private boolean isAutoFinish = false;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_gift_order;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarDarkFont(true).fitsSystemWindows(true).statusBarColor(R.color.white).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new ShopOrderPresenter(this);

        mPresenter.getDetail(userGiftId);

    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(userGiftId);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShopGiftDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        detailBean = bean;

        bottomPrice.setText("¥" + bean.getPrice());

        price.setText("¥" + bean.getPrice());

        title.setText(bean.getName());

        countDownTimer = new CountDownTimer(DateUtils.restDate(bean.getPayExpireTime()), 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countDown.setText(DateUtils.restDate(bean.getPayExpireTime(), 3) + ":" + DateUtils.restDate(bean.getPayExpireTime(), 4));
            }

            @Override
            public void onFinish() {
                isAutoFinish = true;
                showToast("订单超时未支付，自动取消！");
                BusFactory.getBus().post(new Event.OrderRefresh(0));
                finish();
            }
        }.start();


        if (bean.getShopId() == 0) {
            shopName.setText(bean.getOrganizer());
            shopName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        } else {
            shopName.setText(bean.getShopName());
            shopName.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.user_arrow_right_gray), null);
        }

        Glide.with(this)
                .load(bean.getCoverPicUrl())
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(cover);

        date.setText("使用时间：" + bean.getExchangeBeginDate() + " ~ " + bean.getExchangeEndDate());

        address.setText(bean.getAddress());

        introduction.setText(bean.getNote());

        orderNum.setText("订单编号：" + bean.getOrderNumber());

        orderTime.setText("提交时间：" + bean.getCreateTime());
    }

    @Override
    public void paySuccess(ShopPayResultBean bean) {
        dismissLoading();
        payResultBean = bean;
        if (payType == ShopConfig.PAY_TYPE_ALIPAY) {
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(ShopOrderActivity.this);
                    Map<String, String> result = alipay.payV2(payResultBean.getPayBody(), true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {

        }
    }

    @Override
    public void payError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    public void setError(String msg) {

    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        BusFactory.getBus().post(new Event.OrderRefresh(userGiftId));
                        ARouter.getInstance()
                                .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_RESULT)
                                .withInt("id", userGiftId)
                                .withInt("type", 1)
                                .navigation(ShopOrderActivity.this, new NavCallback() {
                                    @Override
                                    public void onArrival(Postcard postcard) {
                                        dismissLoading();
                                        setResult(RESULT_OK);
                                        finish();
                                    }
                                });
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        showToast("支付已取消！");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showAlert(ShopOrderActivity.this, getString(R.string.pay_failed) + payResult);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showAlert(ShopOrderActivity.this, getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        showAlert(ShopOrderActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton(R.string.pay_commit, null)
                .setOnDismissListener(onDismiss)
                .show();
    }

    @OnClick({R2.id.back_btn, R2.id.pay_btn, R2.id.shop_name})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.pay_btn) {
            if (payPopupWindow == null) {
                payPopupWindow = new PayPopupWindow(ShopOrderActivity.this, detailBean.getPrice());
                payPopupWindow.setPayTypeInterface(new PayPopupWindow.PayTypeInterface() {
                    @Override
                    public void payType(int type) {
                        payType = type;
                        showLoading();
                        String sign = Md5Builder.encode(userGiftId + "-" + CommonUtils.getInstance().getUserName() + "-" + CommonUtils.getInstance().getSite() + "-qyhl");
                        mPresenter.pay(userGiftId, CommonUtils.getInstance().getUserName(), sign, payType);
                    }
                });
            } else {
                payPopupWindow.refreshPrice(detailBean.getPrice());
            }

            payPopupWindow.showPopupWindow();
        } else if (viewId == R.id.shop_name) {
            if (detailBean.getShopId() != 0) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                        .withInt("shopId", detailBean.getShopId())
                        .navigation();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }

        if (!isAutoFinish) {
            BusFactory.getBus().post(new Event.OrderRefresh(0));
        }
    }

}
